/*
 * @(#)api.js 1.0.0 14/02/13
 * Copyright 2014© Emagsoftware Technology Co., Ltd. All Rights reserved.
 */

var currentApi;
var systemVariables = {

}

function setContextPath(contextPath) {
    systemVariables.contextPath = contextPath;
}

function getContextPath() {
    return systemVariables.contextPath;
}


    
function initApiCategory() {
    var categorySelect = $("#tree");
    $.each(api_defines, function (i, module) {
        var node =$("<li>").attr("id", module.category);
        node.addClass("node");
        var a = $("<a>").text(module.name);
        node.append(a);
        var children = $("<ul>");
        initChildren(children,module);
        node.append(children);
        
        categorySelect.append(node);

    })
}
function initChildren(children,module) {
        $.each(module.api, function (j, api) {
            var li = $("<li>").text(api.name).addClass("leaf");
            li.attr("category",module.category);
            li.attr("api",api.name);
            children.append(li);
        })

}


function apiClick(category,apiName) {

    var apiModule = $.grep(api_defines, function (module) {
        return module.category === category
    })[0]

    var api = $.grep(apiModule.api, function (api) {
        return api.name === apiName
    })[0];
    currentApi = api;
    if(api.uri)
        $("#apiName").text(api.name + "("+ api.uri+")");
    else
        $("#apiName").text(api.name);

    var fieldTable = $("#businessParams").empty();
    if(api.fields) {
        $.each(api.fields, function (i, field) {
            if (field.required == null) field.required = true;
            fieldTable.append($(template("fieldRow", field)))
        })
        $("#response").empty();

    }
    if(api.rules){
        $.each(api.rules, function (i, rule) {
            fieldTable.append($(template("ruleRow", rule)))
        })
    }

    var apiMethod = api.method;
    //设置method单选钮选中
    if(apiMethod != null && apiMethod != undefined){
        $("input[name=requestMethod][value="+apiMethod+"]").click();
    }
    onchange();

}


function setObjectProperty(object, name, value) {
    if (!value)return;
    object[name] = value;
}

function formatDate(date) {

    var padding = function (value) {
        value = "" + value;
        return value.length == 2 ? value : "0" + value;
    }
    return "" + date.getFullYear() + padding(date.getMonth() + 1) + padding(date.getDate()) + padding(date.getHours()) + padding(date.getMinutes()) + padding(date.getSeconds());

}

function getFormData(){
    var data = {"_showError":true}
    $("#businessForm :input:visible").each(function () {
        var input = $(this)
        setObjectProperty(data, input.attr("name"), input.val())
    });
    return JSON.stringify(data)
}

function onchange(){
    var uri = currentApi.uri;
    var cmd = currentApi.cmd;
    var headers = {};
    var data = getFormData();
}


function submit() {
    var uri = currentApi.uri;
    var headers = {};
    var data = $("#businessForm :input[name='__body']").val();
    var methodType = $("input[name=requestMethod]:checked").val();
    jsonEditor.set({"info":"正在提交"});

    var tableData = {};
    $("#businessForm :input:visible").each(function () {
        var input = $(this)
        setObjectProperty(tableData, input.attr("name"), input.val())
    });
    var pattern = /\{(.+?)\}/;
    for(;;){
        var result = uri.match(pattern);
        if(result == null)break;
        var val = tableData[result[1]];
        uri = uri.replace(result[0],val);
    }
    showRequestInfo(uri, headers, data);
    $.ajax({
        url: uri,
        type: methodType,
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: handleSuccess,
        cache: false,
        error: handleError
    });
}
function submitForm(submitType) {
    var uri = currentApi.uri;
    var headers = {};
    var data = {};
    jsonEditor.set({"info":"正在提交"});

    $("#businessForm :input:visible").each(function () {
        var input = $(this)
        setObjectProperty(data, input.attr("name"), input.val())
    });
    var postBody;
    var processData = true;
    var contentType = null;
    if(currentApi.postBody){
        postBody=$("#businessForm :input[name='__body']").val();
        delete data["__body"];
        var joinSign = uri.indexOf("?")>0?"&":"?";
        for(name in data){
            uri += joinSign + name + "=" + encodeURIComponent(data[name]);
            joinSign = "&";
        }
        data = postBody;
        processData = false;
        contentType="text/plain"
    }else{
        //contentType="application/x-www-form-urlencoded; charset=UTF-8";
        var pattern = /\{(.+?)\}/;
        for(;;){
            var result = uri.match(pattern);
            if(result == null)break;
            var val = data[result[1]];
            uri = uri.replace(result[0],val);
            delete data[result[1]];
        }
    }
    showRequestInfo(uri, headers, data);
    //alert(data.toSource());
    $.ajax({
        url: uri,
        type: submitType,
        data: $("#businessForm").serialize(),
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",
        success: handleSuccess,
        cache: false,
        error: handleError
    });
}
function showRequestInfo(uri, headers, data) {

        $("#params").text("URI   : " + uri + "  \r\nHeader: " + JSON.stringify(headers) + "\r\n" +
            "params: " + data)

}

function handleSuccess(response){
    var json = response;
    jsonEditor.set(json);
    if (currentApi.callback != null) {
        currentApi.callback(json);
    }
}

function handleError(request, textStatus, errorThrown) {
    if(request.getResponseHeader("statuscode") != null){
        var json = jQuery.parseJSON(request.responseText);
        jsonEditor.set(json);
    }
    else{
        jsonEditor.set({"info":"请求出错,status:" + textStatus});
        alert("textStatus:"+textStatus+",errorThrown="+errorThrown)
    }
}





